'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { IconMail, IconBuilding, IconArrowLeft } from "@tabler/icons-react"
import Link from 'next/link'
import { LIVENESS_BASE_URL } from '@/lib/config'

export default function ForgotPasswordPage() {
  const router = useRouter()
  const [email, setEmail] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [step, setStep] = useState<'email' | 'password'>('email') // 移除 'code' 步骤
  const [verificationCode, setVerificationCode] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')

  const handleEmailSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!email) {
      setError('请输入邮箱地址')
      return
    }

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setError('请输入有效的邮箱地址')
      return
    }

    setIsLoading(true)
    setError('')

    try {
      const endpoint = LIVENESS_BASE_URL
      const response = await fetch(`${endpoint}/v1/email/send-code`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email })
      })

      const result = await response.json()

      if (response.ok && result.success) {
        setSuccess(result.message)
        setStep('password') // 改为直接进入 password 步骤
        
        // 开发环境显示验证码
        if (result.code) {
          console.log('🔐 开发环境验证码:', result.code)
        }
      } else {
        setError(result.message || '发送验证码失败')
      }
    } catch (err) {
      console.error('发送验证码失败:', err)
      setError('网络错误，请稍后重试')
    } finally {
      setIsLoading(false)
    }
  }

  const handlePasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!verificationCode || !newPassword || !confirmPassword) {
      setError('请填写所有字段')
      return
    }

    if (verificationCode.length !== 6) {
      setError('验证码应为6位数字')
      return
    }

    if (newPassword.length < 6) {
      setError('密码至少需要6个字符')
      return
    }

    if (newPassword !== confirmPassword) {
      setError('两次输入的密码不一致')
      return
    }

    setIsLoading(true)
    setError('')

    try {
      const endpoint = LIVENESS_BASE_URL
      const response = await fetch(`${endpoint}/v1/email/reset-password`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          email, 
          code: verificationCode, 
          newPassword 
        })
      })

      const result = await response.json()

      if (response.ok && result.success) {
        setSuccess('密码重置成功！正在跳转到登录页面...')
      } else {
        setError(result.message || '密码重置失败')
        return
      }
      
      // 2秒后跳转到登录页
      setTimeout(() => {
        router.push('/login')
      }, 2000)
      
    } catch (err) {
      setError('密码重置失败，请稍后重试')
    } finally {
      setIsLoading(false)
    }
  }

  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEmail(e.target.value)
    if (error) setError('')
    if (success) setSuccess('')
  }

  const handleCodeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setVerificationCode(e.target.value)
    if (error) setError('')
  }

  const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    if (name === 'newPassword') {
      setNewPassword(value)
    } else if (name === 'confirmPassword') {
      setConfirmPassword(value)
    }
    if (error) setError('')
  }

  return (
    <div className="min-h-screen gradient-bg flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* Logo 和标题 */}
        <div className="text-center mb-8">
          <div className="flex items-center justify-center gap-3 mb-4">
            <div className="w-16 h-16 bg-blue-100 rounded-xl flex items-center justify-center shadow-lg">
              <IconBuilding className="w-8 h-8 text-blue-600" />
            </div>
            <div className="text-left">
              <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                医疗空间数字孪生
              </h1>
              <p className="text-sm text-gray-600 dark:text-gray-400">
                Medical Space Digital Twin
              </p>
            </div>
          </div>
          <p className="text-gray-600 dark:text-gray-400">
            重置密码以恢复账号访问
          </p>
        </div>

        {/* 忘记密码表单 */}
        <Card className="glass-effect border border-white/20 dark:border-gray-700/20 shadow-xl">
          <CardHeader className="text-center pb-4">
            <CardTitle className="text-xl font-semibold text-gray-900 dark:text-gray-100">
              {step === 'email' && '忘记密码'}
              {step === 'password' && '重置密码'}
            </CardTitle>
            <CardDescription className="text-gray-600 dark:text-gray-400">
              {step === 'email' && '请输入您的邮箱地址'}
              {step === 'password' && '请输入验证码和新密码'}
            </CardDescription>
          </CardHeader>
          
          <CardContent className="space-y-6">
            {/* 步骤指示器 */}
            <div className="flex items-center justify-center space-x-2">
              <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${
                step === 'email' ? 'bg-blue-600 text-white' : 'bg-green-600 text-white'
              }`}>
                1
              </div>
              <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${
                step === 'email' ? 'bg-gray-200 text-gray-600' : 'bg-blue-600 text-white'
              }`}>
                2
              </div>
            </div>

            {step === 'email' && (
              <form onSubmit={handleEmailSubmit} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="email" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                    邮箱地址 <span className="text-red-500">*</span>
                  </Label>
                  <div className="relative">
                    <IconMail className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                    <Input
                      id="email"
                      type="email"
                      value={email}
                      onChange={handleEmailChange}
                      placeholder="请输入您的邮箱地址"
                      className="pl-10 bg-white/80 dark:bg-gray-800/80 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500"
                      disabled={isLoading}
                    />
                  </div>
                </div>

                {error && (
                  <Alert variant="destructive" className="border-red-200 bg-red-50 dark:bg-red-900/20">
                    <AlertDescription className="text-red-700 dark:text-red-300">
                      {error}
                    </AlertDescription>
                  </Alert>
                )}

                <Button
                  type="submit"
                  className="w-full h-12 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-medium rounded-lg shadow-lg hover:shadow-xl transition-all duration-200"
                  disabled={isLoading}
                >
                  {isLoading ? (
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                      发送中...
                    </div>
                  ) : (
                    '发送验证码'
                  )}
                </Button>
              </form>
            )}

            {step === 'password' && (
              <form onSubmit={handlePasswordSubmit} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="code" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                    验证码 <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="code"
                    type="text"
                    value={verificationCode}
                    onChange={(e) => setVerificationCode(e.target.value)}
                    placeholder="请输入6位验证码"
                    className="text-center text-lg tracking-widest bg-white/80 dark:bg-gray-800/80 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500"
                    disabled={isLoading}
                    maxLength={6}
                  />
                  <p className="text-xs text-gray-500 dark:text-gray-400 text-center">
                    验证码已发送到 {email}
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="newPassword" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                    新密码 <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="newPassword"
                    name="newPassword"
                    type="password"
                    value={newPassword}
                    onChange={handlePasswordChange}
                    placeholder="请输入新密码（至少6个字符）"
                    autoComplete="new-password"
                    className="bg-white/80 dark:bg-gray-800/80 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500"
                    disabled={isLoading}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="confirmPassword" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                    确认密码 <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="confirmPassword"
                    name="confirmPassword"
                    type="password"
                    value={confirmPassword}
                    onChange={handlePasswordChange}
                    placeholder="请再次输入新密码"
                    autoComplete="new-password"
                    className="bg-white/80 dark:bg-gray-800/80 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500"
                    disabled={isLoading}
                  />
                </div>

                {error && (
                  <Alert variant="destructive" className="border-red-200 bg-red-50 dark:bg-red-900/20">
                    <AlertDescription className="text-red-700 dark:text-red-300">
                      {error}
                    </AlertDescription>
                  </Alert>
                )}

                {success && (
                  <Alert className="border-green-200 bg-green-50 dark:bg-green-900/20">
                    <AlertDescription className="text-green-700 dark:text-green-300">
                      {success}
                    </AlertDescription>
                  </Alert>
                )}

                <Button
                  type="submit"
                  className="w-full h-12 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-medium rounded-lg shadow-lg hover:shadow-xl transition-all duration-200"
                  disabled={isLoading}
                >
                  {isLoading ? (
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                      重置中...
                    </div>
                  ) : (
                    '重置密码'
                  )}
                </Button>
              </form>
            )}

            {/* 返回登录链接 */}
            <div className="text-center pt-4 border-t border-gray-200 dark:border-gray-700">
              <Link
                href="/login"
                className="inline-flex items-center gap-2 text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 transition-colors"
              >
                <IconArrowLeft className="w-4 h-4" />
                返回登录
              </Link>
            </div>
          </CardContent>
        </Card>

      </div>
    </div>
  )
}
